package org.jeecg.modules.business.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.netty.util.internal.StringUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.entity.BusMarketObjective;
import org.jeecg.modules.business.entity.BusServiceRepairCategory;
import org.jeecg.modules.business.service.IBusMarketObjectiveService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 销售目标
 * @Author: jeecg-boot
 * @Date:   2023-03-22
 * @Version: V1.0
 */
@Api(tags="销售目标")
@RestController
@RequestMapping("/business/busMarketObjective")
@Slf4j
public class BusMarketObjectiveController extends JeecgController<BusMarketObjective, IBusMarketObjectiveService> {
	@Autowired
	private IBusMarketObjectiveService busMarketObjectiveService;

	/**
	 * 分页列表查询
	 *
	 * @param busMarketObjective
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "销售目标-分页列表查询")
	@ApiOperation(value="销售目标-分页列表查询", notes="销售目标-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusMarketObjective>> queryPageList(BusMarketObjective busMarketObjective,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="12") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusMarketObjective> queryWrapper = QueryGenerator.initQueryWrapper(busMarketObjective, req.getParameterMap());
		Page<BusMarketObjective> page = new Page<BusMarketObjective>(pageNo, pageSize);
		IPage<BusMarketObjective> pageList = busMarketObjectiveService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param busMarketObjective
	 * @return
	 */
	@AutoLog(value = "销售目标-添加")
	@ApiOperation(value="销售目标-添加", notes="销售目标-添加")
	//@RequiresPermissions("business:bus_market_objective_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusMarketObjective busMarketObjective) {
		busMarketObjectiveService.save(busMarketObjective);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param busMarketObjective
	 * @return
	 */
	@AutoLog(value = "销售目标-编辑")
	@ApiOperation(value="销售目标-编辑", notes="销售目标-编辑")
	//@RequiresPermissions("business:bus_market_objective_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusMarketObjective busMarketObjective) {
		busMarketObjectiveService.updateById(busMarketObjective);
		return Result.OK("编辑成功!");
	}

	 /**
	  *   批量添加或修改
	  *
	  * @param busMarketObjectives
	  * @return
	  */
	 @AutoLog(value = "销售目标-批量添加或修改")
	 @ApiOperation(value="销售目标-批量添加或修改", notes="销售目标-批量添加或修改")
	 //@RequiresPermissions("business:bus_market_objective_info:add")
	 @PostMapping(value = "/batchAddOrUpdate")
	 public Result<String> batchAddOrUpdate(@RequestBody List<BusMarketObjective> busMarketObjectives) {
		 BusMarketObjective firstModel = busMarketObjectives.get(0);
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
		 } else {
			 throw new JeecgBootException("当前登录人租户信息错误");
		 }
		 List<BusMarketObjective> newData = new ArrayList<>();
	 	if (firstModel.getId() != null && !firstModel.getId().equals("")){
			//修改
			busMarketObjectiveService.updateBatchById(busMarketObjectives);
		}else{
			//添加
			busMarketObjectives.forEach(item->{
				item.setTenantId(user.getRelTenantIds());
				item.setDelFlag(CommonConstant.DEL_FLAG_0);
				newData.add(item);
			});
			busMarketObjectiveService.saveBatch(newData);
		}
		 return Result.OK("添加成功！");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销售目标-通过id删除")
	@ApiOperation(value="销售目标-通过id删除", notes="销售目标-通过id删除")
	//@RequiresPermissions("business:bus_market_objective_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busMarketObjectiveService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "销售目标-批量删除")
	@ApiOperation(value="销售目标-批量删除", notes="销售目标-批量删除")
	//@RequiresPermissions("business:bus_market_objective_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busMarketObjectiveService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "销售目标-通过id查询")
	@ApiOperation(value="销售目标-通过id查询", notes="销售目标-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusMarketObjective> queryById(@RequestParam(name="id",required=true) String id) {
		BusMarketObjective busMarketObjective = busMarketObjectiveService.getById(id);
		if(busMarketObjective==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busMarketObjective);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busMarketObjective
    */
    //@RequiresPermissions("business:bus_market_objective_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusMarketObjective busMarketObjective) {
        return super.exportXls(request, busMarketObjective, BusMarketObjective.class, "销售目标");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_market_objective_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusMarketObjective.class);
    }

	 /**
	  * 列表查询
	  *
	  * @param busMarketObjective
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "销售目标-列表查询")
	 @ApiOperation(value="销售目标-列表查询", notes="销售目标-列表查询")
	 @GetMapping(value = "/queryList")
	 public Result<List<BusMarketObjective>> queryList(BusMarketObjective busMarketObjective, HttpServletRequest req) {
		 QueryWrapper<BusMarketObjective> queryWrapper = QueryGenerator.initQueryWrapper(busMarketObjective, req.getParameterMap());
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
			 queryWrapper.eq("tenant_id",user.getRelTenantIds());
		 }
		 queryWrapper.eq("del_flag",0);
		 String _yearStr = req.getParameter("year");
		 int _year = 0;
		 if (StringUtil.isNullOrEmpty(_yearStr)){
			 _year = DateUtils.getYear();
		 }else{
			 _year = Integer.parseInt(_yearStr);
		 }

		 List<BusMarketObjective> list = busMarketObjectiveService.list(queryWrapper);
		 if (list.size() <= 0){
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			 Calendar cal = Calendar.getInstance();
			 cal.set(Calendar.YEAR,_year);
			 cal.set(Calendar.MONTH, 0);
			 for(int i=1; i<=12; i++){
				 BusMarketObjective model = new BusMarketObjective();
				 model.setYear(_year);
				 String _month = sdf.format(cal.getTime());
				 cal.add(Calendar.MONTH, 1);
				 model.setMonth(_month.split("-")[1]);
				 list.add(model);
			 }
		 }
		 return Result.OK(list);
	 }

}
